<template>
  <el-card shadow="hover" style="margin-bottom: 10px">
    <el-input style="width: 200px" v-model="data.username" placeholder="输入查询名字" prefix-icon="Search"></el-input>
    <el-button type="primary" style="margin-left: 5px" :prefix-icon="Search" @click="loadByName">查询</el-button>
    <el-button type="success" @click="reset">重置</el-button>
    <!-- <el-button type="primary" @click="hadleNewracer">新增</el-button> -->
    <el-button type="danger" @click="deleteBatch">批量删除</el-button>
  </el-card>

  <!--  <el-card shadow="hover " style="margin-bottom: 10px">-->

  <!--    <el-button type="success">导入</el-button>-->
  <!--    <el-button type="warning">导出</el-button>-->
  <!--  </el-card>-->

  <el-card>
    <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
      <!--      stripe 斑马纹-->
      <!--      prop-->
      <!--      作用：prop 是 <el-table-column> 组件的一个属性，用于指定表格列与数据对象的字段名绑定。-->
      <!--      效果：prop 的值应该与 data 数组中对象的字段名一致，这样表格列才能正确显示对应的数据。-->
      <el-table-column type="selection" width="55"/>
      <el-table-column label="姓名" prop="username"/>
      <el-table-column label="比赛项目" prop="name"/>
      <!-- <el-table-column label="评分人" prop="judgeId"/> -->
      <el-table-column label="评分人" prop="judgeName"/>
      <el-table-column label="成绩" prop="score"/>
      <el-table-column label="评价" prop="comment" show-overflow-tooltip/>

      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="handleUpdate(scope.row)" type="primary" :icon="Edit" circle></el-button>

          <el-button @click="handleDelete(scope.row.id)" type="warning" :icon="Delete" circle v-if="!!scope.row.score"></el-button>

        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 25px">
      <el-pagination
          @size-change="load"
          @current-change="load"
          v-model:current-page="data.currentPage"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
      />
    </div>
  </el-card>

  <el-dialog v-model="data.FormVisible" title="评分情况" width="500px" draggable>

    <el-form :model="data.form" style=" margin-top: 10px;margin-right: 20px">
      <el-form-item label="姓名" label-width="90px">
        <el-input v-model="data.form.username" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="比赛项目" label-width="120px">
        <el-input v-model="data.form.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="成绩" label-width="90px">
        <el-input v-model="data.form.score" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="评价" label-width="90px">
        <el-input v-model="data.form.comment" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.FormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script setup>
import {reactive, ref} from "vue";
import {Delete, Edit, Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const user = ref(JSON.parse(localStorage.getItem('user'))) 
const data = reactive({
  username: '',
  comment:'',
  form: {},
  tableData: [],
  currentPage: 1,
  pageSize: 5,
  total: 0,
  FormVisible: false,
  ids: [],
})

const loadByName =()=> {
  // 点击查询时重置到第一页
  data.currentPage = 1

  request.get('/Score/selectScore', {
    params: {
      pageNum: data.currentPage,
      pageSize: data.pageSize,
      role: 'PARTICIPANT',
      username: data.username.trim() // 传递查询参数
    }
  }).then(res => {
    data.tableData = res.data.list
    data.total = res.data.total
  })
}

const load = () => {
  request.get('/Score/selectScore', {
    params: {
      pageNum: data.currentPage,
      pageSize: data.pageSize,
      comment: data.comment,
      role: 'PARTICIPANT', // 只查询参赛者
      userId: user.value.role =="PARTICIPANT"? user.value.id : null
    }
  }).then(res => {
    data.tableData = res.data.list;
    data.total = res.data.total;
  })

}

load()

const reset = () => {
  data.username = '';
  load()
}

//新增
const hadleNewracer = () => {
  data.FormVisible = true;
  data.form = {};//新增时清空表单，防止上一次数据残留
}

// 新增 和 保存信息
const save = () => {
  data.form.id ? update() : add()//id有值跟新，无添加
}

const add = () => {
  request.post("/Score/add", data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success("操作成功")
      data.FormVisible = false; //添加后 关闭对话框
      load()
    } else {
      ElMessage.error(res.msg)
    }

  })
}

const update = () => {
  let userId = JSON.parse(localStorage.getItem('user'))
  request.put("/Score/update", {...data.form,judgeId:userId.id}).then(res => {
    if (res.code === '200') {
      ElMessage.success("操作成功")
      data.FormVisible = false; //更新后 关闭对话框
      load()
    } else {
      ElMessage.error(res.msg)
    }

  })
}


// 数据编辑
const handleUpdate = (row) => {
  data.form = JSON.parse(JSON.stringify(row))//深拷贝，不直接data.from=row,此时会直接修改
  data.FormVisible = true
}

// 数据删除
const handleDelete = (id) => {
  ElMessageBox.confirm('您确认删除评分信息吗', '删除确认', {type: "warning"}).then(() => {
    request.delete(`/Score/${id}`).then(res => {
      if (res.code === '200') {
        ElMessage.success("操作成功")
        data.FormVisible = false; //删除后 关闭对话框
        load()
      } else {
        ElMessage.error(res.msg)
      }

    })
  }).catch()

}

const handleSelectionChange = (rows) => {//返回所有选中的行对象数组

  //从选中行数组里的里面取出所有行的id组成一个新的数组
  data.ids = rows.map(row => row.id)
  console.log(data.ids)
}

const deleteBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('您确认删除', '删除确认', {type: "warning"}).then(() => {
    request.delete('/user/deleteUserByIdBatch', {data: data.ids}).then(res => {
      if (res.code === '200') {
        ElMessage.success("操作成功")
        data.FormVisible = false; //删除后 关闭对话框
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch()

}

</script>

<style scoped>

</style>
